package com.max.xihu.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Author: Max
 * @Date: 2020-03-21 18:13
 * @Description:
 */
public class ScatteringAndGatheringTest {


    public static void main(String[] args) throws Exception{

        //使用ServerSocketChannel 与 SocketChannel

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        InetSocketAddress inetSocketAddress = new InetSocketAddress(8081);

        //绑定端口并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        SocketChannel socketChannel = serverSocketChannel.accept();
        int msgLen = 8;
        while (true){
            int byteRead = 0;
            while (byteRead < msgLen){
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead:" + byteRead);
                //查看当前的这个buffer的position和limit
                Arrays.asList(byteBuffers).stream().map(byteBuffer -> "position="
                        +byteBuffer.position()+", limit="+byteBuffer.limit()).forEach(System.out::println);
            }
            //将所有的buffer进行flip
            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());

            long byteWrite = 0;
            while(byteWrite < msgLen){
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;

                //将所有的buffer进行clear
                Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());

                System.out.println("byteRead:"+byteRead+" byteWrite="+byteWrite+" msgLen"+msgLen);
            }

        }
    }
}
